package com.wecon.dianping.service.impl;

import com.wecon.dianping.common.BusinessException;
import com.wecon.dianping.common.EmBusinessError;
import com.wecon.dianping.dal.UserMapper;
import com.wecon.dianping.model.User;
import com.wecon.dianping.model.UserExample;
import com.wecon.dianping.service.UserService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * @author Weikang  Wang
 * @program: com.wecon.dianping.service.impl
 * @description:
 * @date 2020/3/10 17:15
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public User getUser(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    /**
     * 用户注册
     *
     * @param user /
     * @return /
     * 事务
     */
    @Override
    @Transactional
    public User register(User user) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {

        String psw = encodeByMd5(user.getPassword());
        user.setPassword(psw);

        try {
            userMapper.insertSelective(user);
        } catch (DuplicateKeyException e) {
            throw new BusinessException(EmBusinessError.REGISTER_DUP_FAIL);
        }

        return getUser(user.getId());
    }

    /**
     * 用户登录
     * @param telphone 手机号
     * @param password 密码
     * @return /
     */
    @Override
    public User login(String telphone, String password) throws UnsupportedEncodingException, NoSuchAlgorithmException, BusinessException {
        String psw = encodeByMd5(password);
        UserExample example = new UserExample();
        example.or().andTelphoneEqualTo(telphone)
                .andPasswordEqualTo(psw);
        List<User> userList = userMapper.selectByExample(example);

        if (userList.isEmpty()) {
            throw new BusinessException(EmBusinessError.LOGIN_FAIL);
        }

        return userList.get(0);
    }

    /**
     * 获取用户数量
     * @return /
     */
    @Override
    public Integer countAllUser() {
        UserExample example = new UserExample();
        example.or().andIdGreaterThan(0);
        return userMapper.countByExample(example);
    }

    /**
     * MD5加密
     *
     * @param str 明文
     * @return 密文
     * @throws NoSuchAlgorithmException     /
     * @throws UnsupportedEncodingException /
     */
    private String encodeByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encode(messageDigest.digest(str.getBytes("utf-8")));
    }
}
